package com.zhongxi.guoyuan.utils;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;

import okhttp3.Call;

public class BaiDuApiTest {

    private static final String BAIDU_APP_KEY = "VHexXA1DGck7BT8o8w03HwxEnvhpcG4N";

    /**
     * 输入中文地址 lng(经度),lat(纬度)
     */
    public static void getLatitude(String address, final OnLocationListener onLocationListener) {
        try {
            // 将地址转换成utf-8的16进制

            String url = "http://api.map.baidu.com/geocoder?address=" + URLEncoder.encode(address, "UTF-8") + "&output=json&&key=" + BAIDU_APP_KEY;

            OkHttpUtils.get().url(url)
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    if (onLocationListener != null) {
                        onLocationListener.onError(e.getMessage().toString());
                    }
                }

                @Override
                public void onResponse(String response, int id) {
                    try {
                        JSONObject mObject = new JSONObject(response);
                        JSONObject mResult = mObject.optJSONObject("result");
                        JSONObject mLocation = mResult.optJSONObject("location");
                        if (onLocationListener != null) {
                            onLocationListener.getLocation(mLocation.optString("lng"), mLocation.optString("lat"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface OnLocationListener {
        void getLocation(String lon, String lat);
        void onError(String error);
    }
}